package com.qc31.baselib.utils

import android.app.Activity
import android.app.ActivityManager
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.text.TextUtils
import android.view.inputmethod.InputMethodManager
import androidx.core.content.FileProvider
import androidx.fragment.app.Fragment
import com.qc31.baselib.R
import java.io.File
import java.util.regex.Pattern
/** 通过状态判断是否有定位 */
fun isNoLocation(state: String): Boolean {
    return when (state) {
        "1", "5", "" -> true
        else -> false
    }
}
/** @author joker @date 2022/8/25$ 14:27$ */
fun sub(string: String, num: Int): String {
    if (string.length > num) {
        return "${string.substring(0, num)}..."
    }
    return string
}

fun subPlate(string: String, num: Int = 14): String {
    if (string.length > num) {
        return string.substring(0, num)
    }
    return string
}


/** 隐藏软键盘 */
fun Activity.hideSoftInput() {
    val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    imm.hideSoftInputFromWindow(window.decorView.windowToken, 0)
}

/**
 * 复制文本到剪贴板
 *
 * @param text 文本
 */
fun copyText(text: CharSequence?, context: Context) {
    val cm =
        context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
    cm.setPrimaryClip(ClipData.newPlainText("text", text))
    context.showToast(context.getString(R.string.toast_copy_success))
}

/** 隐藏软键盘 */
fun Fragment.hideSoftInput() {
    activity?.hideSoftInput()
}

//验证网址
fun isUrl(url: String): Boolean {
    val regex =
        "^([hH][tT]{2}[pP]:/*|[hH][tT]{2}[pP][sS]:/*|[fF][tT][pP]:/*)(([A-Za-z0-9-~]+).)+([A-Za-z0-9-~\\/])+(\\?{0,1}(([A-Za-z0-9-~]+\\={0,1})([A-Za-z0-9-~]*)\\&{0,1})*)$"
    val pattern = Pattern.compile(regex)
    return pattern.matcher(url).matches()
}

/**
 * 复制uri到剪贴板
 *
 * @param uri uri
 */
fun copyUri(context: Context, uri: Uri) {
    val cm =
        context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
    cm.setPrimaryClip(ClipData.newUri(context.getContentResolver(), "uri", uri))
    context.showToast("复制到剪切板成功")
}

/**
 * 获取剪贴板的uri
 *
 * @return 剪贴板的uri
 */
fun getUri(context: Context): Uri? {
    val cm =
        context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
    val clip = cm.primaryClip
    return if (clip != null && clip.itemCount > 0) {
        clip.getItemAt(0).uri
    } else null
}

/**
 * 复制意图到剪贴板
 *
 * @param intent 意图
 */
fun copyIntent(intent: Intent?, context: Context) {
    val cm =
        context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
    cm.setPrimaryClip(ClipData.newIntent("intent", intent))
}

/**
 * 获取剪贴板的意图
 *
 * @return 剪贴板的意图
 */
fun getIntent(context: Context): Intent? {
    val cm = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
    val clip = cm.primaryClip
    return if (clip != null && clip.itemCount > 0) {
        clip.getItemAt(0).intent
    } else null
}

/**
 * 获取剪贴板的文本
 *
 * @return 剪贴板的文本
 */
fun getText(context: Context): CharSequence? {
    val cm =
        context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
    val clip = cm.primaryClip
    return if (clip != null && clip.itemCount > 0) {
        clip.getItemAt(0).coerceToText(context)
    } else null
}

/**
 * 获取文件夹下文件Apk版本信息
 *
 * @param path 文件路径
 * @return
 */
fun getVersionNameFromApk(context: Context, path: String): String {
    val packInfo =
        context.packageManager.getPackageArchiveInfo(path, PackageManager.GET_ACTIVITIES)
            ?: return ""
    return packInfo.versionName
}

/** 私有文件路径 外部为空 就展示内部 */
fun getParentFile(context: Context): File {
    val externalSaveDir = context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)
    return externalSaveDir ?: context.filesDir
}


/** 视频地址 */
fun getVideoPath(context: Context): File {
    val path = "${context.getExternalFilesDir(null)}/video/"
    return mkdirs(path)
}

fun mkdirs(dir: String): File {
    val file = File(dir)
    if (!file.exists()) file.mkdirs()
    return file
}

/** 安装apk */
fun installApk(context: Context, apkPath: String) {
    if (TextUtils.isEmpty(apkPath)) {
        return
    }
    val file = File(apkPath)
    val uri = if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
        // Android 7.0 以下
        Uri.fromFile(file);
    } else {
        MLog.e("安装========================")
        // Android 7.0 及以上
        FileProvider.getUriForFile(context, "${context.packageName}.fileProvider", file);
    }
    val intent = Intent(Intent.ACTION_VIEW)
    val mimeType = "application/vnd.android.package-archive"
    intent.setDataAndType(uri, mimeType) // 设置文件的Uri和Mime Type
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) // 在新栈启动Activity
    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) // 允许三方应用读文件
    context.startActivity(intent)
}

/** 格式话数字精度 */
fun formitNumberD(precision: String, num: Float): Float {
    return String.format("%.${precision}f", num).toFloat()
}

/** 通过状态返回颜色 */
fun stateColor(state: String) = when (state) {
    //报警
    "4", "8", "11", "12" -> "#FF0000"
    //欠费
    "2", "6" -> "#fcdf6b"
    //离线
    "1", "3" -> "#999999"
    //无效定位
    "13" -> "#ff8400"
    //其他
    else -> "#45EB41"
}

/**
 * 判断app是否处于前台
 *
 * @return
 */
fun isAppOnForeground(context: Context): Boolean {
    val activityManager = context.applicationContext
        .getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
    val packageName: String = context.packageName

    /** 获取Android设备中所有正在运行的App */
    val appProcesses = activityManager
        .runningAppProcesses ?: return false
    for (appProcess in appProcesses) {
        // The name of the process that this object is associated with.
        if (appProcess.processName.equals(packageName)
            && appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND
        ) {
            return true
        }
    }
    return false
}

fun formatTo2F(float: Any): String {
    return String.format("%.2f", float)
}

private var lastClickTime: Long = 0

@Synchronized
fun isFastClick(): Boolean {
    val time = System.currentTimeMillis()
    if (time - lastClickTime < 500) {
        return true
    }
    lastClickTime = time
    return false
}